<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>编辑页面</title>
    <link rel="stylesheet" href="../../../component/pear/css/pear.css" />
</head>

<body>
    <form class="layui-form" action="" lay-filter="edit-huixian">
        <div class="mainBox">
            <div class="main-container">
                <div class="layui-form-item">
                    <label class="layui-form-label">姓名</label>
                    <div class="layui-input-block">
                        <input type="text" name="username" id="username" lay-verify="required" autocomplete="off"
                            placeholder="请输用户名" class="layui-input">
                    </div>
                </div>
                <!-- 密码字段注释：编辑时可不显示，避免误改 -->
                <!-- <div class="layui-form-item">
                    <label class="layui-form-label">密码</label>
                    <div class="layui-input-block">
                        <input type="text" name="password" id="password" lay-verify="" autocomplete="off"
                            placeholder="请输入密码" class="layui-input">
                    </div>
                </div> -->
                <div class="layui-form-item">
                    <label class="layui-form-label">手机号</label>
                    <div class="layui-input-block">
                        <input type="text" name="mobile" id="mobile" lay-verify="required|veryifyPhone" autocomplete="off"
                            placeholder="请输入手机号" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">账号状态</label>
                    <div class="layui-input-block">
                        <input type="radio" name="status" value="1" title="启用" lay-skin="tag" checked>
                        <input type="radio" name="status" value="0" title="禁用" lay-skin="tag">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">管理员类型</label>
                    <div class="layui-input-block">
                        <input type="radio" name="is_admin" value="1" title="普通用户" lay-skin="tag" checked>
                        <input type="radio" name="is_admin" value="0" title="管理员" lay-skin="tag">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">排序号</label>
                    <div class="layui-input-block">
                        <input type="text" name="sort_num" id="sort_num" lay-verify="required|veryify_sort"
                            autocomplete="off" value="0" placeholder="请输入排序号" class="layui-input">
                    </div>
                </div>
            </div>
        </div>
        <div class="bottom">
            <div class="button-container">
                <button type="submit" class="pear-btn pear-btn-primary pear-btn-sm" lay-submit=""
                    lay-filter="base-save">
                    <i class="layui-icon layui-icon-ok"></i>
                    提交
                </button>
                <button type="reset" class="pear-btn pear-btn-sm">
                    <i class="layui-icon layui-icon-refresh"></i>
                    重置
                </button>
            </div>
        </div>
    </form>
    <script src="../../../component/com/api.js"></script>
    <script src="../../../component/com/auth.js"></script>
    <script src="../../../component/layui/layui.js"></script>
    <script src="../../../component/pear/pear.js"></script>
    <script>
        layui.use(['form', 'jquery', 'layer'], function () {
            let form = layui.form;
            let $ = layui.jquery;
            let layer = layui.layer;
            let API_BASE_URL = apiConfig.baseUrl;
            let token = window.localStorage.getItem("token") || window.sessionStorage.getItem("token");
            let urlParams = new URLSearchParams(window.location.search);
            let id = urlParams.get('id'); // 编辑的账号ID
            let initialData = {}; // 存储【初始数据】（用于对比差异）

            // 1. 页面加载时：获取后端数据并保存初始数据
            if (id) {
                $.ajax({
                    url: `${API_BASE_URL}/common/account/${id}/`,
                    dataType: 'json',
                    contentType: 'application/json',
                    type: 'get',
                    headers: {
                        "Authorization": token
                    },
                    success: function (result) {
                        if (result.code == 200) {
                            // 保存【初始数据】（深拷贝，避免引用污染）
                            initialData = JSON.parse(JSON.stringify({
                                username: result.data.username,
                                mobile: result.data.mobile,
                                is_admin: result.data.is_admin.toString(), // 单选框值是字符串，需统一类型
                                status: result.data.status.toString(),     // 同上：后端返回数字，表单值是字符串
                                sort_num: result.data.sort_num.toString()  // 排序号可能是数字，表单值是字符串
                            }));

                            // 渲染表单数据
                            form.val("edit-huixian", {
                                'username': result.data.username,
                                'mobile': result.data.mobile,
                                'is_admin': result.data.is_admin.toString(), // 类型统一为字符串
                                'status': result.data.status.toString(),     // 类型统一为字符串
                                'sort_num': result.data.sort_num.toString()  // 类型统一为字符串
                            });
                        } else {
                            // 错误处理：提取具体错误信息
                            let errorMessage = result.message;
                            if (result.data && typeof result.data === 'object') {
                                const firstKey = Object.keys(result.data)[0];
                                if (firstKey) errorMessage = result.data[firstKey][0];
                            }
                            layer.msg(errorMessage, { icon: 2, time: 2000 });
                        }
                    },
                    error: function () {
                        layer.msg("网络请求异常，无法加载数据", { icon: 2, time: 2000 });
                    }
                })
            }

            // 2. 表单验证规则：排序号必须是正整数
            form.verify({
                veryify_sort: function (value) {
                    if (!/^\d+$/.test(value)) return "请输入正整数！";
                    if (parseInt(value) < 0) return "请输入正整数！";
                },
                // 补充：手机号格式验证（原代码缺少 veryifyPhone 实现）
                veryifyPhone: function (value) {
                    if (!/^1[3-9]\d{9}$/.test(value)) return "请输入正确的11位手机号！";
                }
            });

            // 3. 核心：对比【初始数据】与【当前数据】是否有差异
            function isDataChanged(currentData) {
                // 遍历所有需要对比的字段（与 initialData 字段对应）
                const compareFields = ['username', 'mobile', 'is_admin', 'status', 'sort_num'];
                for (let field of compareFields) {
                    // 初始数据中的字段值 vs 当前表单中的字段值
                    if (initialData[field] !== currentData[field]) {
                        return true; // 有一个字段不同，即视为数据变更
                    }
                }
                return false; // 所有字段都相同，无变更
            }

            // 4. 表单提交事件：仅当数据有变更时才发起请求
            form.on('submit(base-save)', function (data) {
                // 获取【当前表单数据】（已自动处理为字符串类型）
                const currentData = data.field;

                // 第一步：对比数据是否有变更
                if (!isDataChanged(currentData)) {
                    layer.msg("未修改任何数据，无需提交", { icon: 3, time: 1500 });
                    return false; // 不发起请求，直接返回
                }

                // 第二步：数据有变更，发起 PATCH 请求
                $.ajax({
                    url: `${API_BASE_URL}/common/account/${id}/`,
                    data: JSON.stringify(currentData),
                    dataType: 'json',
                    contentType: 'application/json',
                    type: 'patch',
                    headers: {
                        "Authorization": token
                    },
                    success: function (result) {
                        if (result.code == 200) {
                            layer.msg(result.message, {
                                icon: 1,
                                time: 1000
                            }, function () {
                                // 关闭当前弹窗并刷新父页面表格
                                parent.layer.close(parent.layer.getFrameIndex(window.name));
                                parent.layui.table.reload("base-table");
                            });
                        } else {
                            // 错误处理：提取具体错误信息
                            let errorMessage = result.message;
                            if (result.data && typeof result.data === 'object') {
                                const firstKey = Object.keys(result.data)[0];
                                if (firstKey) errorMessage = result.data[firstKey][0];
                            }
                            layer.msg(errorMessage, { icon: 2, time: 2000 });
                        }
                    },
                    error: function () {
                        layer.msg("网络请求异常，提交失败", { icon: 2, time: 2000 });
                    }
                });

                return false; // 阻止表单默认提交行为
            });
        })
    </script>
</body>
</html>